package com.tjetc;

import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class workCount {

    public static class MyMapper extends Mapper<Text, LongWritable,Text,LongWritable>{
        @Override
        protected void map(Text key, LongWritable value, Context context) throws IOException, InterruptedException {
            String line = value.toString();
            String[] split = line.split(" ");//请在此处填写代码
            for (String word : split) {
                Text k2=new Text(word);//请在此处填写代码
                LongWritable v2=new LongWritable(1L);//请在此处填写代码
                context.write(k2,v2);
            }
        }
    }


    public static class MyReducer extends Reducer<Text,LongWritable,Text,LongWritable>{
        @Override
        protected void reduce(Text k2, Iterable<LongWritable> v2s,
                              Reducer<Text, LongWritable, Text,
                                      LongWritable>.Context context) throws IOException,
                InterruptedException {
            Long count=0L;//请在此处填写代码
            for (LongWritable times : v2s) {
                count+=times.get();
            }
            LongWritable v3=new LongWritable(count);//请在此处填写代码
            context.write(k2,v3);
        }
    }


    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf, workCount.class.getSimpleName());
        //必须指定
        job.setJarByClass(workCount.class);

        //指定本业务job要使用的Mapper业务类
        job.setMapperClass(MyMapper.class);//请在此处填写代码
        //指定mapper输出数据的<k2,v2>的类型
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(LongWritable.class);

        //指定本业务job要使用的Reducer业务类
        job.setReducerClass(MyReducer.class);//请在此处填写代码
        //指定reducer输出数据的<k3,v3>的类型
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(LongWritable.class);

        //输入数据来自哪里
        FileInputFormat.setInputPaths(job, new Path(args[0]));
        //输出数据写到哪里
        FileOutputFormat.setOutputPath(job, new Path(args[1]));

        //true表示将运行进度等信息及时输出给用户
        boolean res = job.waitForCompletion(true);
        System.exit(res ? 0 : 1);

    }

}
